import java.util.Scanner;

public class Solution_02 {
    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //结果链表的链表头
        ListNode result = new ListNode(0);
        //指向上述链表当前节点
        ListNode cur = result;
        //进位
        int carry = 0;
        while (l1!=null || l2!=null){
            int x = l1==null ? 0 : l1.val;
            int y = l2==null ? 0 : l2.val;
            //求和，对应位的数字加前一位的进位
            int sum = x + y + carry;

            carry = sum/10;
            sum = sum%10;
            cur.next = new ListNode(sum);

            //后移
            cur = cur.next;
            if (l1 != null){
                l1 = l1.next;
            }
            if (l2 != null){
                l2 = l2.next;
            }
        }
        //最后一步加完后如果有进位
        if (carry == 1) {
            cur.next = new ListNode(carry);
        }
        //避免出现[0,7,0,8]
        if (result.next != null){
            //result指针后移
            result = result.next;
        }
        return  result;
    }
}

